import re
import os
from collections import defaultdict
from typing import Dict, List, Tuple


class MarkdownSectionExtractor:
    def __init__(self, file_path: str):
        self.file_path = file_path
        self.content = self._read_file()
        self.sections = self._extract_sections()

    def _read_file(self) -> List[str]:
        """读取Markdown文件内容"""
        try:
            with open(self.file_path, 'r', encoding='utf-8') as f:
                return f.readlines()
        except FileNotFoundError:
            print(f"错误: 文件不存在 - {self.file_path}")
            return []
        except Exception as e:
            print(f"读取文件时出错: {str(e)}")
            return []

    def _extract_sections(self) -> Dict[Tuple, Dict]:
        """
        提取所有章节及其完整内容
        返回格式: {(level, title): {'content': str, 'children': []}}
        """
        if not self.content:
            return {}

        # 正则表达式匹配Markdown标题
        heading_pattern = re.compile(r'^(#{1,6})\s+(.*)$')

        # 存储所有标题及其位置
        headings = []
        for line_num, line in enumerate(self.content, 1):
            match = heading_pattern.match(line.strip())
            if match:
                level = len(match.group(1))
                title = match.group(2).strip()
                headings.append({
                    'level': level,
                    'title': title,
                    'line': line_num
                })

        if not headings:
            return {}

        # 构建章节树
        section_tree = {}
        current_path = []

        # 添加所有标题到章节树
        for heading in headings:
            # 确定当前章节路径
            while current_path and current_path[-1][0] >= heading['level']:
                current_path.pop()

            current_path.append((heading['level'], heading['title']))
            section_tree[tuple(current_path)] = {
                'content': '',
                'children': []
            }

        # 为每个章节收集内容
        current_section = None
        content_lines = []

        # 查找所有标题行号
        heading_lines = [h['line'] for h in headings]

        for line_num, line in enumerate(self.content, 1):
            if line_num in heading_lines:
                # 保存上一章节内容
                if current_section:
                    section_tree[current_section]['content'] = ''.join(content_lines).strip()
                    content_lines = []

                # 设置新章节
                for path in section_tree.keys():
                    if path[-1][0] == headings[heading_lines.index(line_num)]['level'] and \
                            path[-1][1] == headings[heading_lines.index(line_num)]['title']:
                        current_section = path
                        break
            elif current_section:
                # 添加内容到当前章节
                content_lines.append(line)

        # 保存最后一个章节的内容
        if current_section and content_lines:
            section_tree[current_section]['content'] = ''.join(content_lines).strip()

        # 构建层级关系
        for path in list(section_tree.keys()):
            if len(path) > 1:
                parent_path = path[:-1]
                if parent_path in section_tree:
                    section_tree[parent_path]['children'].append(path)

        return section_tree

    def get_all_sections(self) -> Dict[Tuple, Dict]:
        """获取所有章节"""
        return self.sections

    def get_sections_by_level(self, level: int) -> List[Dict]:
        """获取特定层级的所有章节"""
        sections = []
        for path, section in self.sections.items():
            if path[-1][0] == level:
                sections.append({
                    'level': level,
                    'title': path[-1][1],
                    'content': section['content']
                })
        return sections

    def get_min_level_sections(self) -> List[Dict]:
        """获取最小层级的所有章节"""
        if not self.sections:
            return []

        # 找到最大层级（最小标题）
        max_level = max(path[-1][0] for path in self.sections.keys())
        return self.get_sections_by_level(max_level)

    def get_full_content_by_level(self, level: int) -> Dict[str, str]:
        """获取特定层级所有章节的完整内容（标题+内容）"""
        result = {}
        for section in self.get_sections_by_level(level):
            full_content = f"{'#' * section['level']} {section['title']}\n\n{section['content']}"
            result[section['title']] = full_content
        return result

    def print_section_structure(self):
        """打印章节结构"""
        if not self.sections:
            print("没有找到章节")
            return

        print("Markdown文档结构:")
        print("=" * 60)

        # 从根章节开始
        root_sections = [p for p in self.sections.keys() if len(p) == 1]
        for path in root_sections:
            self._print_section(path, 0)

    def _print_section(self, path: Tuple, indent: int):
        """打印单个章节及其子章节"""
        section = self.sections.get(path)
        if not section:
            return

        level, title = path[-1]
        print(f"{'  ' * indent}层级 {level}: {title}")

        # 打印内容摘要
        if section['content']:
            content_preview = section['content'][:100].replace('\n', ' ')
            if len(section['content']) > 100:
                content_preview += "..."
            print(f"{'  ' * (indent + 1)}内容预览: {content_preview}")
        else:
            print(f"{'  ' * (indent + 1)}无内容")

        # 递归打印子章节
        for child_path in section['children']:
            self._print_section(child_path, indent + 1)

    def save_all_sections(self, output_dir: str):
        """将所有章节保存为单独的文件"""
        if not self.sections:
            print("没有章节数据可保存")
            return

        os.makedirs(output_dir, exist_ok=True)

        for path, section in self.sections.items():
            level, title = path[-1]

            # 创建安全文件名
            safe_title = re.sub(r'[\\/*?:"<>|]', '', title)
            path_str = "_".join([f"{lvl}_{t}" for lvl, t in path])
            file_name = f"{path_str}.md"
            file_path = os.path.join(output_dir, file_name)

            # 构建完整内容
            full_content = f"{'#' * level} {title}\n\n{section['content']}"

            # 写入文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(full_content)

            print(f"已保存: {file_path}")


def read_md():
    # 配置Markdown文件路径
    md_file = "D:\\hbyt\\AI智能投标\\markdown_output\\markdown_output1.md"

    # 初始化解析器
    extractor = MarkdownSectionExtractor(md_file)

    if not extractor.content:
        return

    # print(f"解析Markdown文件: {md_file}")
    # print("=" * 60)

    # 1. 打印文档结构
    # extractor.print_section_structure()

    # print("\n" + "=" * 60)

    # 2. 获取所有层级2的章节
    content = []
    level_2_sections = extractor.get_sections_by_level(2)
    print(f"层级2的章节 (共{len(level_2_sections)}个):")
    for i, section in enumerate(level_2_sections, 1):
        print(f"{i}. {section['title']}")
        print(f"   内容摘要: {section['content'][:100000]}...")
        if section['content'][:100000] is not "":
            content.append(section['content'][:100000])

    print("\n" + "=" * 60)

    # 3. 获取所有层级3的章节
    level_3_sections = extractor.get_sections_by_level(3)
    print(f"层级3的章节 (共{len(level_3_sections)}个):")
    for i, section in enumerate(level_3_sections, 1):
        print(f"{i}. {section['title']}")
        print(f"   内容摘要: {section['content'][:100000]}...")
        if section['content'][:100000] is not None:
            content.append(section['content'][:100000])
    print(content)

    print("\n" + "=" * 60)

    # 4. 获取最小层级章节
    # min_sections = extractor.get_min_level_sections()
    # min_level = min_sections[0]['level'] if min_sections else "无"
    # print(f"最小层级章节 (层级 {min_level}, 共{len(min_sections)}个):")
    # for i, section in enumerate(min_sections, 1):
    #     print(f"{i}. {section['title']}")
    #
    # print("\n" + "=" * 60)

    # 5. 保存所有章节为单独文件
    # output_dir = "D:\\hbyt\\AI智能投标\\markdown_output\\all_sections"
    # extractor.save_all_sections(output_dir)

    # print("\n操作完成")


if __name__ == "__main__":
    read_md()